package com.order.controller;
import com.order.hit.crossover.platform.common.bean.Notice;
import com.order.hit.crossover.platform.common.bean.order.Order;
import com.order.hit.crossover.platform.common.bean.order.OrderState;
import com.order.hit.crossover.platform.common.bean.order.OrderType;
import com.order.hit.crossover.platform.common.bean.order.Quotation;
import com.order.hit.crossover.platform.common.dao.OrderDao;
import com.order.hit.crossover.platform.common.dao.QuotationDao;
import com.order.hit.crossover.platform.common.utils.PFResponse;
import com.order.service.OrderService;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * @author Lei
 * @version 0.1
 * @date 2020/8/4
 */

@RestController
@RequestMapping("/orderService")
public class OrderController {

    private static Logger logger = LogManager.getLogger(OrderController.class);

    @Autowired
    @Qualifier("OrderServiceImpl")
    private OrderService orderService;


    // 添加订单, 店面自己添加
    @PostMapping("/addAOrder")
    public PFResponse addOneOrder(@RequestBody OrderDao orderDao) {
        orderDao.setOrderId(UUID.randomUUID().toString().substring(24));
        int code = 0;
        String message = "";
        try {
            this.orderService.addOneOrder(orderDao);
            code = 200;
            message = "添加成功";
        } catch (Exception e) {
            code = 500;
            message = "添加失败";
        }
        return new PFResponse().code(code).message(message);
    }

    // 删除订单
    @DeleteMapping("/delete/{orderId}")
    public PFResponse deleteOrderByid(@PathVariable("orderId") String orderId) {
        int code = 0;
        String message = "";
        try {
            this.orderService.deleteOrder(orderId);
            code = 200;
            message = "删除成功";
        } catch (Exception e) {
            code = 500;
            message = "删除失败";
        }
        return new PFResponse().message(message).code(code);
    }

    // 获取所有订单
    @GetMapping("/getAllOrderByStoreId/{storeid}")
    public PFResponse getAllOrder(@PathVariable("storeid") String id){
        return new PFResponse().data(this.orderService.getALlorder(id));
    }

    // 获取特定订单信息，针对店家可以查看
    @GetMapping("/getOrderById/{id}")
    public PFResponse getOrderByid(@PathVariable("id") String id) {
        Order order = this.orderService.getOrderByid(id);
        PFResponse resp = new PFResponse();
        resp.code(200);
        resp.message("查询成功！");
        resp.data(order);
        return resp;
    }

    // 获取某一店家的所有求购订单 超出时间的也算
    @GetMapping("/getStoreBuyOrder/{storeId}")
    public PFResponse getBuyOrderofstore(@PathVariable("storeId") String storeId) {
        List<Order> list = this.orderService.getBuyOrderofstore(storeId);
        PFResponse resp = new PFResponse();
        resp.code(200);
        resp.message("查询成功！");
        resp.data(list);
        return resp;
    }

    // 获取某一店家的所有求售订单 超出时间的也算
    @GetMapping("/getStoreSoldOrder/{storeId}")
    public PFResponse getSoldOrderofstore(@PathVariable("storeId") String storeId) {
        List<Order> list = this.orderService.getSoldOrderofstore(storeId);
        PFResponse resp = new PFResponse();
        resp.code(200);
        resp.message("查询成功！");
        resp.data(list);
        return resp;
    }


    //获取所有求售/求购 订单 没有超出时间的
    @GetMapping("/getAllOrderByType/{type}")
    public PFResponse getAllOrderByType(@PathVariable("type") String type) {
        List<Order> list = type.equalsIgnoreCase(OrderType.ORDER_BUY.toString()) ? this.orderService.getAllOrder(OrderType.ORDER_BUY.toString()) : this.orderService.getAllOrder(OrderType.ORDER_SOLD.toString());
        PFResponse response = new PFResponse();
        response.code(200);
        response.data(list);
        return response;
    }

    @GetMapping("/getAllOrderByTypeDisplay/{type}")
    public PFResponse getAllOrderByTypeDisplay(@PathVariable("type") String type){
        List<Order> list = type.equalsIgnoreCase(OrderType.ORDER_BUY.toString()) ? this.orderService.getAllOrder(OrderType.ORDER_BUY.toString()) : this.orderService.getAllOrder(OrderType.ORDER_SOLD.toString());
        Iterator<Order> iterator = list.iterator();
        while (iterator.hasNext()){
            if (!iterator.next().getOrderState().equals(OrderState.ORDER_DISPLAY)){
                iterator.remove();
            }
        }
        PFResponse response = new PFResponse();
        response.code(200);
        response.data(list);
        return response;
    }

    //获取所有正在展示的求售/求购的订单，在展示台上展示
    @GetMapping("/getAlldisplayOrder/{type}")
    public PFResponse getAllDisplayOrder(@PathVariable("type") String type) {
        List<Order> list = type.equalsIgnoreCase(OrderType.ORDER_BUY.toString()) ? this.orderService.getAllDisplayOrder(OrderType.ORDER_BUY.toString()) : this.orderService.getAllDisplayOrder(OrderType.ORDER_SOLD.toString());
        PFResponse response = new PFResponse();
        response.code(200);
        response.data(list);
        return response;
    }


    //更改订单状态
    @PutMapping("/updateOrderState")
    public PFResponse updataOrderType(@RequestParam("orderId") String orderId, @RequestParam("state") String state) {
        int code = 0;
        String m = "";
        try {
            this.orderService.updateOrderState(orderId, state);
            code = 200;
            m = "状态更新成功";
        } catch (Exception e) {
            code = 500;
            m = "状态更新失败";
            e.printStackTrace();
        }
        return new PFResponse().code(code).message(m);
    }


    @PutMapping("/successOrder/{orderId}/{quotationId}")
    public PFResponse successOrder(@PathVariable("orderId")String orderId, @PathVariable("quotationId")String quotationId){
        int code = 0;
        String m = "";
        try {
            this.orderService.successOrder(orderId, quotationId);
            Order order = this.orderService.getOrderByid(orderId);
            Quotation q = (Quotation)new RestTemplate().exchange("http://quo:18085/quotationService/getQuotionByQuotionId/"+quotationId, HttpMethod.GET, new HttpEntity<>(new HttpHeaders()), PFResponse.class).getBody().get("data");
            q.setQuotationState(OrderState.getNameByCode(7));
            new RestTemplate().exchange(
                    "http://quo:18085/quotationService/updateQuo/",
                    HttpMethod.PUT,
                    new HttpEntity<>(QuotationDao.getQuatationDao(q), new HttpHeaders()),
                    PFResponse.class);
            //  生成通知信息
            String success_info1 = "您的订单(" + q.getGood().getGoodName() + ")已成交， 请前往本店求购/求售查看。";
            Notice success_notice1 = new Notice(success_info1,0,0,order.getStore().getStoreId());
            new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(success_notice1, new HttpHeaders()), PFResponse.class);
            String success_info2 = "您的报价单(" + q.getGood().getGoodName() + ")已成交， 请前往报价单购买/出售查看。";
            Notice success_notice2 = new Notice(success_info2,0,0,q.getStore().getStoreId());
            new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(success_notice2, new HttpHeaders()), PFResponse.class);
            // 其余没有超时得报价单需要更改为 未被接受得状态

            List<Quotation> list = (List<Quotation>)new RestTemplate().exchange(
                    "http://quo:18085/quotationService/getQuotionByOrderId/"+orderId,
                    HttpMethod.GET,
                    new HttpEntity<>(new HttpHeaders()),
                    PFResponse.class).getBody().get("data");

            for(Quotation quotation: list){
                if(quotation.getQuotationState().equals(OrderState.QUOTATION_DISPLAY)){
                    quotation.setQuotationState(OrderState.QUOTATION_NOT_ACCEPT);
                    new RestTemplate().exchange(
                            "http://quo:18085/quotationService/updateQuo/",
                            HttpMethod.PUT,
                            new HttpEntity<>(QuotationDao.getQuatationDao(quotation), new HttpHeaders()),
                            PFResponse.class);
//                    this.quotationService.update(QuotationDao.getQuatationDao(quotation));

                    //  生成通知信息
                    String fail_info = "您的报价单(" + quotation.getGood().getGoodName() + ")已失败， 请前往报价单购买/出售查看。";
                    Notice fail_notice = new Notice(fail_info,0,0,quotation.getStore().getStoreId());
                    new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(fail_notice, new HttpHeaders()), PFResponse.class);
                }
            }
            code = 200;
            m = "订单成功";
        } catch (Exception e) {
            code = 500;
            m = "订单失败";
            e.printStackTrace();
        }
        return new PFResponse().code(code).message(m);
    }
}
